package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.entity.Product;
import cn.tedu.coolshark.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
public class ProductController {

    @Value("${dirPath}")
    private String dirPath;

    @Autowired(required = false)
    ProductMapper mapper;

    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product) {

        System.out.println("product = " + product);
        //设置商品的发布时间为当前系统时间
        product.setCreated(new Date());
        //调用mapper的insert方法
        mapper.insert(product);

    }

    @RequestMapping("/product/select")
    public List<Product> select() {

        return mapper.select();

    }

    @RequestMapping("/product/delete")
    public void delete(int id) {

        System.out.println("id = " + id);
        //通过id查询到商品的图片路径
        String url = mapper.selectUrlById(id);
        String filePath = dirPath + "/" + url;
        new File(filePath).delete();
        //删除数据库里面的数据
        mapper.deleteById(id);

    }

    @RequestMapping("/product/select/index")
    public List<Product> selectIndex() {

        return mapper.selectIndex();

    }

    @RequestMapping("/product/select/top")
    public List<Product> selectTop() {

        List<Product> list = mapper.selectTop();
        for (Product p : list) {

            if (p.getTitle().length() > 3) {

                p.setTitle(p.getTitle().substring(0, 3) + "...");

            }

        }

        return list;

    }

    @RequestMapping("/product/select/category")
    public List<Product> selectByCid(int cid) {

        System.out.println("cid = " + cid);
        return mapper.selectByCid(cid);

    }

    @RequestMapping("/search")
    public List<Product> search(String wd) {

        System.out.println("wd = " + wd);
        return mapper.selectByWd(wd);

    }

    @RequestMapping("/product/selectById")
    public Product selectById(int id){

        //让浏览量+1
        mapper.updateViewCount(id);
        return mapper.selectById(id);

    }

}
